package com.weipai.springboot.module.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weipai.springboot.base.interceptor.LoginHandlerInterceptor;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.Admin;
import com.weipai.springboot.model.Customer;
import com.weipai.springboot.model.sys.User;
import com.weipai.springboot.module.service.UserService;
import com.weipai.springboot.shiro.AppCacheDao;
import com.weipai.springboot.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 用户信息sesion操作工具类
 * 为了适应spring-session 序列化，session中存储的除基本类型外的其他对象均采用Map对象
 *
 * @author gyt
 * @date 2017年8月26日 下午4:26:48
 */
@Component
public class SessionUserUtil {
    private static final Logger logger = LoggerFactory.getLogger(SessionUserUtil.class);
//    private static Session getSession() {
//        return SecurityUtils.getSubject().getSession();
//    }
    @Autowired
    private UserService userService;
    @Autowired
    private AppCacheDao appCacheDao;

    /**
     * 获取登录用户信息
     */
    @SuppressWarnings("unchecked")
    public Customer getUserAttr() {
        User user = getUser();
        Customer customer = user.getUser();
        return customer;
    }

    public Admin getAdminAttr() {
        User user = getUser();
        Admin admin = user.getUser();
        return admin;
    }

    public User getUser() {
        int type = this.getUserType();
        User user = null;
        if (User.CUSTOMER == type) {
            String token = getAuthenticationToken();
            logger.info("getUser:token"+token);
            user = appCacheDao.getUser(token);
            logger.info("getUser:user"+ JSONObject.toJSONString(user));
            if (user == null) {
                String username = PasswordHelper.getUserName(token);
                user = userService.getCustomerUser(username);
                if (user != null) {
                    appCacheDao.save(token, user);
                }
            }
        } else {
                Session session = SecurityUtils.getSubject().getSession();
            user = (User) session.getAttribute(User.KEY);
        }
        return user;
    }


    /**
     * 设置session属性
     *
     * @param key
     * @param value
     */
    public <T> void set(String key, T value) {
        getUser().put(key, value);
    }

    /**
     * 获取session属性值
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T> T get(String key) {
        return (T) getUser().get(key);
    }

    public int getUserType() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String typeStr = null;
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            if(key.equals(User.HEADER_TYPE_KEY)){
                typeStr = request.getHeader(key);
            }
        }
        int type = User.CUSTOMER;
        logger.info("typeStr:"+typeStr);
        try {
//
            if(null!=typeStr){
                type = Integer.valueOf(typeStr);
                /*type = User.EMPLOYEE;*/
            }
//            else{
//                type = Integer.valueOf(typeStr);
//            }
        } catch (NumberFormatException e) {
            logger.warn("default user type is customer");
        }
        logger.info("getUserType:"+type);
        return type;
    }

    public String getAuthenticationToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        logger.info("getAuthenticationToken:"+request.getHeader(LoginHandlerInterceptor.AUTH_TOKEN_HEADER));
        return request.getHeader(LoginHandlerInterceptor.AUTH_TOKEN_HEADER);
    }
}
